package components

import (
	"strings"
	"regexp"
	"library/common"
	"fmt"
	"time"
	"github.com/gaoyue1989/sshexec"
	"library/ssh"
)

const SSHTIMEOUT = 3600
const SSHWorker = 10
const SSHREMOTETIMEOUT = 600
const SSHACCOUNT = "root"


func GetExecCommand(cmd string) string {
	tasks := strings.Split(cmd, "\n")
	if len(tasks) == 0 {
		return ""
	}
	for i := range tasks {
		tasks[i] = strings.Replace(tasks[i], "\n", "", -1)
		tasks[i] = strings.Replace(tasks[i], "\r", "", -1)
	}
	cmds := []string{}
	for _, task := range tasks {
		if strings.Trim(task, " ") != "" {
			taskStr := task
			if strings.Trim(taskStr, " ") != "" {
				cmds = append(cmds, taskStr)
			}
		}
	}
	cmdStr := strings.Join(cmds, " && ")
	return cmdStr
}

func GetHosts(host string) []string {
	hostsStr := host
	reg := regexp.MustCompile(`(\d+)\.(\d+)\.(\d+)\.(\d+)`)
	hosts := reg.FindAll([]byte(hostsStr), -1)
	res := []string{}
	for _, host := range hosts {
		if !common.InList(string(host), res) {
			res = append(res, string(host))
		}

	}
	return res
}

/**
* 结束进程
 */
func KillProcess(execCmd string,hosts []string) error {
	command := fmt.Sprintf("ps -ef |grep %s| grep -v grep  |awk '{print $2}' |xargs kill -9", execCmd)
	sshExecAgent := sshexec.SSHExecAgent{}
	sshExecAgent.Worker = SSHWorker
	sshExecAgent.TimeOut = time.Duration(SSHREMOTETIMEOUT) * time.Second
	_, err := sshExecAgent.SshHostByKey(hosts, SSHACCOUNT, command)
	if err != nil {
		return err
	}
	return nil
}

/**
* 执行本地宿主机命令
 */
func RunLocalCommand(command string) (sshexec.ExecResult, error) {
	s, err := gopubssh.CommandLocal(command, SSHTIMEOUT)
	return s, err
}


/**
 * 清理空间
 */
func CleanUpLocal(desDir string) error {
	cmd := fmt.Sprintf("rm -rf %s ",desDir )
	_, err := RunLocalCommand(cmd)
	return err
}

/**
 * 清理远端空间
 */
func CleanUpReleasesVersion(desDir ,hosts[]string) error {
	cmd := fmt.Sprintf("rm -rf %s ",desDir )
	sshExecAgent := sshexec.SSHExecAgent{}
	sshExecAgent.Worker = SSHWorker
	sshExecAgent.TimeOut = time.Duration(SSHREMOTETIMEOUT) * time.Second
	_, err := sshExecAgent.SshHostByKey(hosts, SSHACCOUNT, cmd)
	if err != nil {

	}
	return err
}

/**
 * 测试ssh连接
 *
 */
func  TestSsh(hosts []string) error {
	cmd := "id"
	sshExecAgent := sshexec.SSHExecAgent{}
	sshExecAgent.Worker = SSHWorker
	sshExecAgent.TimeOut = time.Duration(SSHREMOTETIMEOUT) * time.Second
	_, err := sshExecAgent.SshHostByKey(hosts, SSHACCOUNT, cmd)
	if err != nil {

	}
	return err
}
